package com.yl.demo.base.config.shiro;

import com.yl.demo.utils.DESUtil;
import com.yl.demo.utils.MD5Util;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义 密码验证类
 * @author YL
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {


    private final static Logger logger = LoggerFactory.getLogger(CustomCredentialsMatcher.class);

    private final static MD5Util MD_5_UTIL = new MD5Util();


    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        //自定义登录验证
        //用户登录的用户名称+密码 加密
        String pwdOuter = DESUtil.encryptBasedDes(token.getUsername() + MD_5_UTIL.MD532(String.valueOf(token.getPassword())));
        //数据库 用户名称+密码 加密
        String pwdInner = DESUtil.encryptBasedDes(token.getUsername() + getCredentials(info));
        logger.info("用户MD5加密密碼：{}", MD_5_UTIL.MD532(String.valueOf(token.getPassword())));
        logger.info("用户pwdOuter密文：{}", pwdOuter);
        logger.info("用户pwdInner密文：{}", pwdInner);
        if (!pwdOuter.equalsIgnoreCase(pwdInner)) {
            logger.info("帐号或密码不正确！用户：{}", token.getUsername());
            //throw new AccountException("帐号或密码不正确！");
        }
        //将密码加密与系统加密后的密码校验，内容一致就返回true,不一致就返回false
        logger.info("密码校验:" + pwdOuter.equalsIgnoreCase(pwdInner) + "  OR " + equals(pwdOuter, pwdInner));
        return equals(pwdOuter, pwdInner);
    }
}
